package com.know.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import my.db.QueryHelper;

import com.know.entity.Users;
import com.know.entity.Comments;
import com.kzw.bean.Record;
import com.kzw.dao.support.Page;

public class CommentDao {

	/**
	 * 查询前Num条评论
	 * @param num
	 * @return
	 */
	public List<Comments> newlist(int num) {
		String sql = "select * from comments  order by comment_date DESC  limit "+num;
		List<Comments> list=QueryHelper.query(Comments.class, sql);
		QueryHelper.load(list, "user", "user_id", Users.class);
		return list;
	}
	/**
	 * 得到分页评论（评论整取未解决）
	 * @param page
	 * @param article_id 
	 * @return
	 */
	public Record findPage(Page<Comments> page, Long article_id) {
		Record record = new Record();
		String sql = "select * from comments where article_id=? and parent_comment_id=0";
		if(StringUtils.isNotBlank(page.getOrderBy())) {
			sql += String.format(" order by %s %s", page.getOrderBy(), page.getOrder());
		}
		//读出文章ID相同的父级评论
		List<Comments> parentList = QueryHelper.queryPage(Comments.class, sql, page.getPageNo(), page.getPageSize(),article_id);
		//进行递归，将评论父子关系排序。
		
		List<Comments> list=getTree_comments(parentList);
		QueryHelper.load(list, "user", "user_id", Users.class);
		//设置临时变量 user_temp  父级用户
		String user_temp="";
		for (Comments comment : list) {
			if(comment.getParent_comment_id()==0)
			{
				user_temp=comment.getUser().getUser_name();//获得父级用户名
			}
			else
			{
				comment.getUser().setUser_temp(user_temp);
			}
			/*设置默认头像*/
			String src="img/user.jpg";
			if(comment.getUser().getUser_photo()==null||comment.getUser().getUser_photo().equals(""))
				comment.getUser().setUser_photo(src);
			
				
		}
		String sql2 = sql.toLowerCase().replaceFirst("select .*? from", "select count(*) from");
		long count = QueryHelper.stat(sql2,article_id);
		page.setTotalCount((int)count);
		count=page.getTotalPages();
		record.setCount(count);
		record.setData(list);

		return record;
	}
	/**
	 * 得到一个加载子评论的评论树
	 * @param list
	 * @return
	 */
	private List<Comments> getTree_comments(List<Comments> list) {
		
		List<Comments> tree=new ArrayList<Comments>();
		for (Comments comment : list) {
			String sql ="select * from comments where parent_comment_id=?";
			tree.add(comment);
			List<Comments> childs=QueryHelper.query(Comments.class, sql,comment.getComment_id());
			tree.addAll(childs);
		}
		return tree;
	}
	/**
	 * 保存新留言
	 * @param comment
	 */
	public void save(Comments comment) {
		String sql="INSERT INTO comments VALUES (null,? ,?, ?, ?, ?, ?)";
		QueryHelper.update(sql, comment.getUser_id(),comment.getArticle_id(),comment.getComment_like_count(),comment.getComment_date(),comment.getComment_content(),comment.getParent_comment_id());
	}
	
	

	
	

}
